<?php
namespace App\Admin\Requests\System;

use Closure;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\ValidationException;
use Illuminate\Validation\Rule;
use App\Admin\Models\User;

class UserUpdateRequest extends FormRequest
{

    protected $stopOnFirstFailure = true;

    public function rules(): array
    {
        $user_id = $this->route('id');
        $unique = Rule::unique(User::class)->ignore($user_id);

        return [
            'email'     => [
                'sometimes',
                'required_without:mobile',
                'nullable',
                'email', 
                $unique,
            ],
            'mobile'     => [
                'sometimes', 
                'required_without:email',
                'nullable', 
                'digits:11', 
                $unique,
            ],
            'name'      => [
                'sometimes',
                'alpha_num',
                'between:2,20',
            ],
            'password'  => [
                'sometimes',
                'nullable',
                'alpha_num',
                'between:6,20',
            ],
            'profile_photo_path'    => [
                'sometimes', 
                'nullable', 
                // 'url',
            ],
            'status'    => [
                'sometimes', 
                'in:0,1',
                function (string $attribute, mixed $value, Closure $fail) use($user_id) {
                    if( $user_id==1 && $value!=1 ){
                        $fail("初号超级管理员不能被禁用{$attribute}");
                    }
                },
            ],

            //附加字段
            'role_ids'   => ['nullable', 'array'],
            'role_ids.*'   => ['sometimes', 'integer', 'exists:system_role,id'],
        ];
    }

    public function attributes()
    {
        return [
            'email' => '邮箱',
            'mobile' => '手机号',
        ];
    }

    public function messages()
    {
        return [
            'unique' => ':attribute已存在',
            'email.required_without' => ':attribute和:values必须至少设置一项',
            'mobile.required_without' => ':attribute和:values必须至少设置一项',
        ];
    }
}
